
import Foundation
import hpple
import SwiftyJSON

extension KMTool {
    
    
    //MARK: 修改状态栏颜色
    static func changeStatusColor(color:UIColor) {
        
        let statusBarWindow = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
        let statusBar = statusBarWindow.value(forKey: "statusBar") as! UIView
        if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) {
            statusBar.backgroundColor = color
        }
    }
    
    //MARK: 判断是否为iPhoneX系列
    static func isNewiPhone() -> Bool {
        
        if Int(ScreenH/ScreenW * 100) == 216 {
            return true
        }
        
        return false
    }
    
    
    //MARK: 解析Html数据为数组
    fileprivate static func htmlToArray(data:Data,htmlElement:String,attributes:String) -> [String] {
        
        let hpple = TFHpple.init(htmlData: data)
        let liArray = hpple?.search(withXPathQuery: htmlElement) as NSArray?
        
        var elements = [String]()
        
        if attributes == "text" {
            for element in liArray! {
                let title = (element as? TFHppleElement)?.text()
                elements.append(title ?? "")
            }
        }else if attributes == "src" || attributes == "href" ||  attributes == "value" {
            for element in liArray! {
                let title = (element as? TFHppleElement)?.object(forKey: attributes)
                elements.append(title ?? "")
            }
        }else if attributes == "span" {
            for element in liArray! {
                let title = (element as? TFHppleElement)?.firstChild(withTagName: attributes).text()
                elements.append(title ?? "")
            }
        }
        
        
        
        return elements
    }
    
    //MARK: 解析Html数据为模型
    /// -data : 解析的html数据
    /// -elements : 解析的html元素
    /// -attributes : 解析的html元素的属性
    /// -keys : 字典键值
    static func htmlToModel(data:Data,elements:[String],attributes:[String],keys:[String]) -> [[String:String]] {
        
        var dicArray = [[String:String]]()
        var elementArray = [[String]]()
        
        for i in 0..<elements.count {
            
            let array = KMTool.htmlToArray(data: data, htmlElement: elements[i], attributes: attributes[i])
            elementArray.append(array)
        }
        
        for _ in 0..<elementArray[0].count {
            dicArray.append([String:String]())
        }
        
        for i in 0..<elementArray.count {
            
            let array = elementArray[i]
            for j in 0..<array.count {
                dicArray[j][keys[i]] = array[j]
            }
        }
        
        return dicArray
    }
    
    //MARK: 解析Html数据为模型
    /// -data : 解析的html数据
    /// -elements : 解析的html元素
    /// -attributes : 解析的html元素的属性
    static func htmlToArray(data:Data,elements:[String],attributes:[String]) -> [[String]] {
        
        var elementArray = [[String]]()
        
        for i in 0..<elements.count {
            
            let array = KMTool.htmlToArray(data: data, htmlElement: elements[i], attributes: attributes[i])
            elementArray.append(array)
        }
        
        return elementArray
    }
    
    
    //MARK: 网络节点移除
    static func removeHtmlElement(classNames:[String]) -> String {
        
        var removeElement = ""
        
        for className in classNames {

            removeElement += "document.getElementsByClassName('\(className)')[0].remove();"
        }
        
        
        
        return removeElement
    }
    
    //MARK: 网络节点移除
    static func removeHtmlElementForId(idNames:[String]) -> String {
        
        var removeElement = ""
        
        for idName in idNames {
            
            removeElement += "document.getElementById('\(idName)').remove();"
        }
        
        return removeElement
    }
    
    
    
    //MARK: 通过银行选照片
    static func selectBankImage(bankName:String) -> String {
        
        if bankName == "" {
            return ""
        }
        
        let moreBankArray = [["name":CITICBank,"image":"zhongxin"],["name":PufaBank,"image":"pufa"],["name":GuangfaBank,"image":"guangfa"],["name":EverbrightBank,"image":"guangda"],["name":PeaceBank,"image":"pingan"],["name":CitiBank,"image":"huaqi"],["name":GuangzhouBank,"image":"guangzhou"],["name":ZheshangBank,"image":"zheshang"],["name":ChinaMerchantsBank,"image":"zhaoshang"],["name":BankofCommunications,"image":"jiaotong"],["name":MinshengBank,"image":"minsheng"],["name":IndustrialBank,"image":"xingye"],["name":HSBCBank,"image":"huaxia"],["name":ShanghaiBank,"image":"shanghai"],["name":BankofChina,"image":"boc"],["name":ABC,"image":"abc"],["name":ICBC,"image":"icbc"],["name":Constructionbank,"image":"ccb"],["name":Postalsaving,"image":"youzheng"],["name":PostalBank,"image":"youzheng"],["name":BaoshangBank,"image":"baoshang"],["name":BankofBeijing,"image":"beijing"],["name":ChongqingBank,"image":"chongqing"],["name":HSBC,"image":"huifeng"],["name":StandardCharteredBank,"image":"zhada"],["name":agriculturalBank,"image":""],["name":PinganHewlett,"image":"pinganhuipu"],["name":ShanghaiRuralCommercial,"image":"shanghainongshang"]]
        
        //索引
        var name = "yinlian"
        
        for model in moreBankArray {
            
            if (bankName as NSString).range(of: model["name"]!).location != NSNotFound {
                
                name = model["image"]!
                break
            }
        }
        
        return name
    }
    
    //MARK: 通过id查询银行
    static func searchBankForId(id:String) -> String {
        
        let bankArray = [["id":"23","name":Constructionbank],["id":"11","name":MinshengBank],["id":"13","name":HSBCBank],["id":"2","name":PufaBank],["id":"3","name":GuangfaBank],["id":"6","name":CitiBank],["id":"15","name":BankofChina],["id":"1","name":CITICBank],["id":"10","name":BankofCommunications],["id":"12","name":IndustrialBank],["id":"4","name":EverbrightBank],["id":"5","name":PeaceBank],["id":"9","name":ChinaMerchantsBank],["id":"21","name":ABC],["id":"7","name":GuangzhouBank],["id":"28","name":HSBC],["id":"29","name":StandardCharteredBank],["id":"24","name":Postalsaving],["id":"26","name":BankofBeijing],["id":"14","name":ShanghaiBank],["id":"8 ","name":ZheshangBank],["id":"25","name":BaoshangBank],["id":"22","name":ChongqingBank],["id":"27","name":ICBC]]

        for model in bankArray {
            if model["id"]! == id {
                return model["name"]!
            }
        }
        
        return ""
    }
    
    //MARK: 银行联系方式
    /**
     name: 银行名称
     phone: 电话号码
     cellPhone: 手机号码
     bill: 账单
     lines: 额度
     points: 积分
     debt: 欠款
     
     **/
    static func bankContactDetails(bankName:String)-> [String:String]? {
        
        let bankArray = [CITICBank:["name":CITICBank,"phone":"95558","cellPhone":"106980095558","bill":"ZD","billTip":"ZD+信用卡后四位","lines":"YE","linesTip":"YE+信用卡后四位","points":"JF","pointsTip":"JF+信用卡后四位"],BankofChina:["name":BankofChina,"phone":"95566","cellPhone":"95566","lines":"XYKKYED#1234#CNY/USD/JPY","linesTip":"XYKKYED#+信用卡号后四位#+货币码（CNY/USD/JPY）","points":"17#","pointsTip":"17#+信用卡号后四位"],ABC:["name":ABC,"phone":"95599","cellPhone":"95599"],ICBC:["name":ICBC,"phone":"95588","cellPhone":"95588","bill":"CXZD#信用卡号#短信密码","billTip":"CXZD#+信用卡号#+短信密码","lines":"CXED#信用卡号#短信密码","linesTip":"CXED#+信用卡号#+短信密码","points":"CXJF#信用卡号#短信密码","pointsTip":"CXJF#+信用卡号#+短信密码"],Constructionbank:["name":Constructionbank,"phone":"95533","cellPhone":"95533","bill":"CCZD#","billTip":"CCZD#+信用卡号后四位","lines":"CCED#","linesTip":"CCED#+信用卡号后四位","points":"CCJF#","pointsTip":"CCJF#+信用卡号后四位"],PostalBank:["name":PostalBank,"phone":"95580","cellPhone":"95580","bill":"YECX#","billTip":"YECX#+信用卡号后四位","lines":"EDCX#","linesTip":"EDCX#+信用卡号后四位","points":"JFCX#","pointsTip":"JFCX#+信用卡号后四位"],PufaBank:["name":PufaBank,"phone":"95528","cellPhone":"95528","bill":"ZDCX 1234","billTip":"ZDCX+空格+信用卡号后四位","points":"JFCX 1234","pointsTip":"JFCX+空格+信用卡号后四位","debt":"DQQK 1234","debtTip":"DQQK+空格+信用卡号后四位"],GuangfaBank:["name":GuangfaBank,"phone":"95508","cellPhone":"95508","bill":"XZD","billTip":"XZD+信用卡号后四位+查询年月（yyyyMM）","lines":"XED","linesTip":"XED+信用卡号后四位","points":"XJF","pointsTip":"XJF+信用卡号后四位"],EverbrightBank:["name":EverbrightBank,"phone":"95595","cellPhone":"95595","bill":"账单","billTip":"账单+信用卡号后四位","lines":"额度","linesTip":"额度+信用卡号后四位","points":"积分","pointsTip":"积分+信用卡号后四位"],PeaceBank:["name":PeaceBank,"phone":"95511","cellPhone":"95511","bill":"8602","billTip":"8602","lines":"8601","linesTip":"8601"],GuangzhouBank:["name":GuangzhouBank,"phone":"96699","cellPhone":"96699"],CitiBank:["name":CitiBank,"phone":"8008301880","cellPhone":"8008301880"],ZheshangBank:["name":ZheshangBank,"phone":"95527","cellPhone":"95527"],ChinaMerchantsBank:["name":ChinaMerchantsBank,"phone":"95555","cellPhone":"95555","bill":"#ZD","billTip":"#ZD","lines":"#ED","linesTip":"#ED","points":"#JF","pointsTip":"#JF"],BankofCommunications:["name":BankofCommunications,"phone":"95559","cellPhone":"95559","bill":"CC账单#","billTip":"CC账单#+信用卡号后四位","lines":"CC额度#","linesTip":"CC额度#+信用卡号后四位","points":"CC积分#","pointsTip":"CC积分#+信用卡号后四位"],MinshengBank:["name":MinshengBank,"phone":"95568","cellPhone":"106902895568","bill":"ZD","billTip":"ZD+信用卡号后四位","lines":"ED","linesTip":"ED+信用卡号后四位","points":"JF","pointsTip":"JF+信用卡号后四位"],IndustrialBank:["name":IndustrialBank,"phone":"95561","cellPhone":"95561","bill":"30","billTip":"30+信用卡号后四位"],HSBCBank:["name":HSBCBank,"phone":"95577","cellPhone":"95577"],ShanghaiBank:["name":ShanghaiBank,"phone":"95594","cellPhone":"95594"],BaoshangBank:["name":BaoshangBank,"phone":"95352","cellPhone":"95352"],BankofBeijing:["name":BankofBeijing,"phone":"95526","cellPhone":"95526"],ChongqingBank:["name":ChongqingBank,"phone":"96899","cellPhone":"96899"],HSBC:["name":HSBC,"phone":"95366","cellPhone":"95366"],StandardCharteredBank:["name":StandardCharteredBank,"phone":"8008208088","cellPhone":"8008208088"]]
        
        return bankArray[bankName]
    }
    
    //MARK: 生成记录
    static func generateRecords(idString:String) {
        
        
        
//        if KMTool.isSignIn() {
//
//            //用户记录
//            KMTool.requestMethod(.post, URLString: url_record, parameters: ["user_name":KMTool.stringForEnumKey(.phone) ?? "","id":recordId], success: { (value, json) in
//
//                if json["status"].stringValue == "0" {
//
//                }else{
//                    KMTool.showText(_text: json["data"].stringValue)
//                }
//
//            }) {
//
//            }
//        }else{ //游客记录
//
//            KMTool.requestData(URLString: url_touristsRecord, parameters: ["id":recordId,"device":"1","series":"0"], progress: nil) { (string) in
//
//            }
//        }
        
        getIPAddresses(idString: idString)
        
        
        
        
    }
    
    //MARK: 获取手机ip和位置
    static func getIPAddresses(idString:String) {
        
        var city = ""
        
        if let currentCity = KMTool.stringForEnumKey(.currentCity) {
            
            city = currentCity
        }else{
            let ipUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=myip"
            let url = URL.init(string: ipUrl)
            let data = NSData.init(contentsOf: url!)
            
            if data == nil {
                
                getIPAddresses(idString: idString)
                return
            }
            
            let ipDic = JSON.init(data!)
            MyLog(ipDic)
            
            city = ipDic["data"]["city"].stringValue
        }
        
        
        
        let recordId = idString.replacingOccurrences(of: webUrl + "/mobile/details/i", with: "")
        
        KMTool.requestData(URLString: url_commonRecord, parameters: ["id":recordId,"series":"0","user_name":KMTool.stringForEnumKey(.phone) ?? "","location":city]) { (string) in
            
            
        }
        
    }
    
    //MARK: 获取当前位置
    static func getCuttentLocation(block:((String)->Void)?) {
        
        KMTool.locationManager.desiredAccuracy = kCLLocationAccuracyBest //设置精准度
        KMTool.locationManager.locationTimeout = 2 //定位超时
        KMTool.locationManager.reGeocodeTimeout = 2 //逆地址超时
        KMTool.locationManager.requestLocation(withReGeocode: false) {(location, reGeocode, error) in
            
            let code  = (error as NSError?)?.code
            
            if code == AMapLocationErrorCode.locateFailed.rawValue {
                KMTool.showText(_text: (error?.localizedDescription)!)
            }else if code == AMapLocationErrorCode.reGeocodeFailed.rawValue || code == AMapLocationErrorCode.timeOut.rawValue || code == AMapLocationErrorCode.cannotFindHost.rawValue || code == AMapLocationErrorCode.badURL.rawValue || code == AMapLocationErrorCode.notConnectedToInternet.rawValue || code == AMapLocationErrorCode.cannotConnectToHost.rawValue {
                
                KMTool.showText(_text: (error?.localizedDescription)!)
              
            }else{
                
                MyLog(location?.coordinate)
                if location == nil {
                    return
                }
                let geocoder = CLGeocoder()
                geocoder.reverseGeocodeLocation(location!, completionHandler: { (array, error) in
                    if array != nil && (array?.count)! > 0 {
                        let placemark = array?.first
                        
                        //获取城市
                        var city = placemark?.locality
                        if city != nil {
                            MyLog(city)
                            MyLog(placemark?.name)
                            MyLog(placemark?.subLocality)
                            MyLog(placemark?.country)
                            MyLog(placemark?.administrativeArea)
                        }else{
                            city = placemark?.administrativeArea
                            MyLog(city)
                            MyLog(placemark?.name)
                            MyLog(placemark?.subLocality)
                            MyLog(placemark?.country)
                            MyLog(placemark?.administrativeArea)
                        }
                        
                        if block != nil {
                            
                            city = city?.replacingOccurrences(of: "市", with: "")
                            block!(city!)
                        }
                        
                        city = city?.replacingOccurrences(of: "市", with: "")
                        KMTool.setObject(city, forEnumKey: .currentCity)
                    }
                })
                
            }
            
            
            
        }
    }
    
    //MARK: 获取所有省份
    static func getAllProvince()->[String] {
        
        let plistPath = Bundle.main.path(forResource: "city", ofType: "plist")
        let array = NSArray.init(contentsOfFile: plistPath!) as? [[String:Any]]
        
        var provinceArray = [String]()
        
        for model in array! {
            
            provinceArray.append(model["state"] as! String)
        }
        
        return provinceArray
    }
    
    //MARK: 通过省份获取城市
    static func getCityForProvince(province:String)->[String] {
        
        let plistPath = Bundle.main.path(forResource: "city", ofType: "plist")
        let array = NSArray.init(contentsOfFile: plistPath!) as? [[String:Any]]
        
        var cityArray = [String]()
        
        for model in array! {
            
            if province == model["state"] as! String {
                cityArray = model["cities"] as! [String]
            }
        }
        
        return cityArray
    }


    
}
